package com.xz.xzutils.module.toolwindow.tabs;

import com.intellij.DynamicBundle;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.ActionPopupMenu;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.ui.JBColor;
import com.intellij.ui.JBSplitter;
import com.xz.xzutils.actions.AnActionId;
import com.xz.xzutils.utils.EditorUtils;
import com.xz.xzutils.utils.SqlParser;
import com.xz.xzutils.utils.dto.SqlDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.util.List;
import javax.swing.*;

/**
 * <p>
 * sql 解析页面
 * </p>
 *
 * @author DONG.WANG17@HAND-CHINA.COM
 * @since 2025-01-04 13:34
 */
@Slf4j
public class SqlParserTab extends BaseTab {
    private final DynamicBundle messageBundle = new DynamicBundle(SqlParserTab.class, "messages.MyPlugin");
    private final JPanel sqlParserPanel;
    private final Editor logInputEditor;
    private final Editor sqlViewer;
    private final JButton parseButton;
    private final JButton copyButton;
    private final EditorUtils editorUtils = EditorUtils.getInstance();

    public SqlParserTab(ToolWindow toolWindow) {
        super("Sql解析");
        setTabName(messageBundle.getMessage("plugin.tab.sqlparser.title"));
        // 初始化组件
        logInputEditor = createEditor();
        sqlViewer = createSqlViewer();
        parseButton = new JButton(messageBundle.getMessage("plugin.tab.sqlparser.button.parse"));
        copyButton = new JButton(messageBundle.getMessage("plugin.tab.sqlparser.button.copy"));
        JBSplitter splitter = new JBSplitter(true, 0.5f);
        splitter.setFirstComponent(logInputEditor.getComponent());
        splitter.setSecondComponent(sqlViewer.getComponent());


        // TODO 添加选择日志文件的按钮

        sqlParserPanel = new JPanel(new BorderLayout());
        // 设置splitter占更多空间
        sqlParserPanel.add(splitter, BorderLayout.CENTER);
        // 添加按钮的事件监听器
        parseButton.addActionListener(e -> {
            sqlViewer.getComponent().repaint();
            editorUtils.reset(sqlViewer);
            String inputText = logInputEditor.getDocument().getText();
            try {
                List<SqlDTO> sqlList = SqlParser.parse(inputText);
                if (CollectionUtils.isEmpty(sqlList)) {
                    editorUtils.addLine(sqlViewer, "当前日志文本未解析到 sql 语句", JBColor.RED);
                } else {
                    renderSqlViewer(sqlViewer, sqlList);
                }
            } catch (Exception ex) {
                editorUtils.addLine(sqlViewer, ex.getMessage(), JBColor.RED);
            }
        });
        copyButton.addActionListener(e -> {
            // TODO 赋值光标所在行 （通过右键触发）
            String outputText = sqlViewer.getDocument().getText();
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(outputText), null);
            Messages.showInfoMessage("复制成功", "XzUtils");
        });
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(parseButton);
        buttonPanel.add(copyButton);
        sqlParserPanel.add(buttonPanel, BorderLayout.SOUTH);
        super.setJComponent(sqlParserPanel);
    }

    private Editor createSqlViewer() {
        EditorFactory editorFactory = EditorFactory.getInstance();
        FileTypeManager fileTypeManager = FileTypeManager.getInstance();
        FileType fileType = fileTypeManager.getFileTypeByExtension("sql");
        Editor editor = editorFactory.createEditor(editorFactory.createDocument(""), null, fileType, true);
        // 不允许换行
        editor.getSettings().setUseSoftWraps(false);
        editor.getSettings().setWrapWhenTypingReachesRightMargin(false);
        // 添加右键操作
        // -- 复制当前行
        ActionManager actionManager = ActionManager.getInstance();
        DefaultActionGroup actionGroup = new DefaultActionGroup();
        actionGroup.add(actionManager.getAction(AnActionId.CopyCurrentLineAction));
        actionGroup.add(actionManager.getAction(AnActionId.CopyAction));
        ActionPopupMenu actionPopupMenu = actionManager.createActionPopupMenu(ActionPlaces.EDITOR_POPUP, actionGroup);
        editorUtils.addComponentPopupMenu(editor, actionPopupMenu.getComponent());
        return editor;
    }

    private Editor createEditor() {
        EditorFactory editorFactory = EditorFactory.getInstance();
        FileTypeManager fileTypeManager = FileTypeManager.getInstance();
        FileType fileType = fileTypeManager.getFileTypeByExtension("log");
        Editor editor = editorFactory.createEditor(editorFactory.createDocument(""), null, fileType, false);
        // 不允许换行
        editor.getSettings().setUseSoftWraps(false);
        editor.getSettings().setWrapWhenTypingReachesRightMargin(false);
        return editor;
    }


    // TODO 对于参数不一致的报错进行 UI 提示，将 【?】部分高亮
    private void renderSqlViewer(Editor editor, List<SqlDTO> sqlList) {
        // 一行一行添加文本
        for (SqlDTO sqlDTO : sqlList) {
            if (sqlDTO.getParseSuccess()) {
                editorUtils.addLine(editor, sqlDTO.getSqlKey());
                editorUtils.addLine(editor, sqlDTO.getSql());
            } else {
                editorUtils.addLine(editor, sqlDTO.getSqlKey(), JBColor.YELLOW);
                editorUtils.addLine(editor, "# SQL语句:\t" + sqlDTO.getTemplateSql(), JBColor.RED);
                editorUtils.addLine(editor, "# SQL参数:\t" + sqlDTO.getParameters(), JBColor.RED);
                editorUtils.addLine(editor, "# 提示信息:\t" + sqlDTO.getMessage(), JBColor.RED);
            }
        }
    }

}
